package com.ug.common.exception;

import com.ug.common.enums.ErrorCode;
import com.ug.common.response.ResponseMessage;
import com.ug.common.response.ResponseMessageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Author LY
 * @create 2024/7/16 16:53
 * @Description 配置全局异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 全局自定义异常处理，统一返回状态码
     */
    @ExceptionHandler(SystemException.class)
    public ResponseMessage<String> handleSystemException(SystemException e) {
        logger.error("服务器抛出了异常：{}", e);
        return ResponseMessageFactory.getErrorResponseMessage(e.getCode(), e.getMessage());
    }

    /**
     * 全局异常处理，统一返回状态码
     */
    @ExceptionHandler(Exception.class)
    public ResponseMessage<String> handleException(Exception e){
        logger.error("服务器抛出了异常：{}", e);
        return ResponseMessageFactory.getErrorResponseMessage(ErrorCode.SERVER_EXCEPTION.getCode(), e.getMessage());
    }
}
